import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/anime_provider.dart';
import '../../data/datasources/anime_local_datasource.dart';
import '../../core/di/service_locator.dart';

/// 缓存管理页面
class CacheManagementPage extends StatefulWidget {
  const CacheManagementPage({super.key});

  @override
  State<CacheManagementPage> createState() => _CacheManagementPageState();
}

class _CacheManagementPageState extends State<CacheManagementPage> {
  late AnimeLocalDataSource _localDataSource;
  Map<String, dynamic>? _cacheInfo;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _localDataSource = getIt<AnimeLocalDataSource>();
    _loadCacheInfo();
  }

  Future<void> _loadCacheInfo() async {
    setState(() => _isLoading = true);
    
    try {
      final cacheInfo = await _localDataSource.getCacheInfo();
      setState(() {
        _cacheInfo = cacheInfo;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('获取缓存信息失败: $e')),
        );
      }
    }
  }

  Future<void> _clearCache() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清除缓存'),
        content: const Text('确定要清除所有缓存数据吗？这将删除已保存的动漫列表和详情。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      setState(() => _isLoading = true);
      
      try {
        await _localDataSource.clearCache();
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('缓存已清除')),
          );
          
          // 重新加载缓存信息
          await _loadCacheInfo();
        }
      } catch (e) {
        setState(() => _isLoading = false);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('清除缓存失败: $e')),
          );
        }
      }
    }
  }

  Future<void> _cleanExpiredCache() async {
    setState(() => _isLoading = true);
    
    try {
      final cleanedCount = await _localDataSource.cleanExpiredCache();
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已清理 $cleanedCount 个过期缓存项')),
        );
        
        // 重新加载缓存信息
        await _loadCacheInfo();
      }
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('清理过期缓存失败: $e')),
        );
      }
    }
  }

  Future<void> _refreshAllData() async {
    setState(() => _isLoading = true);
    
    try {
      final animeProvider = Provider.of<AnimeProvider>(context, listen: false);
      await animeProvider.refreshAllData();
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('数据刷新完成')),
        );
        
        await _loadCacheInfo();
      }
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('刷新数据失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('缓存管理'),
        actions: [
          IconButton(
            onPressed: _isLoading ? null : _loadCacheInfo,
            icon: const Icon(Icons.refresh),
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _buildContent(),
    );
  }

  Widget _buildContent() {
    if (_cacheInfo == null) {
      return const Center(
        child: Text('无法加载缓存信息'),
      );
    }

    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        // 缓存统计卡片
        _buildCacheStatsCard(),
        const SizedBox(height: 16),
        
        // 缓存操作卡片
        _buildCacheActionsCard(),
        const SizedBox(height: 16),
        
        // 缓存详情卡片
        _buildCacheDetailsCard(),
      ],
    );
  }

  Widget _buildCacheStatsCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '缓存统计',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: _buildStatItem(
                    '总条目',
                    '${_cacheInfo!['total_entries']}',
                    Icons.storage,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    '列表缓存',
                    '${_cacheInfo!['list_entries']}',
                    Icons.list,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    '详情缓存',
                    '${_cacheInfo!['detail_entries']}',
                    Icons.info,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            _buildStatItem(
              '缓存大小',
              '${_cacheInfo!['cache_size_mb']} MB',
              Icons.folder,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          size: 32,
          color: Theme.of(context).colorScheme.primary,
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
        ),
        Text(
          label,
          style: Theme.of(context).textTheme.bodySmall,
        ),
      ],
    );
  }

  Widget _buildCacheActionsCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '缓存操作',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _isLoading ? null : _refreshAllData,
                    icon: const Icon(Icons.refresh),
                    label: const Text('刷新数据'),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: _isLoading ? null : _cleanExpiredCache,
                    icon: const Icon(Icons.cleaning_services),
                    label: const Text('清理过期'),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: _isLoading ? null : _clearCache,
                icon: const Icon(Icons.delete_forever),
                label: const Text('清除所有缓存'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.error,
                  foregroundColor: Theme.of(context).colorScheme.onError,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCacheDetailsCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '缓存详情',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 16),
            _buildDetailRow('缓存有效期', '${_cacheInfo!['cache_valid_duration_minutes']} 分钟'),
            _buildDetailRow('最旧缓存', _formatDateTime(_cacheInfo!['oldest_entry'])),
            _buildDetailRow('最新缓存', _formatDateTime(_cacheInfo!['newest_entry'])),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                  ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Text(
              value,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
          ),
        ],
      ),
    );
  }

  String _formatDateTime(dynamic dateTime) {
    if (dateTime == null) return '无';
    
    if (dateTime is DateTime) {
      return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    }
    
    return dateTime.toString();
  }
} 